package com.lou.springboot.interceptor;

import com.lou.springboot.entity.Reader;
import com.lou.springboot.entity.Track;
import com.lou.springboot.service.ReaderService;
import com.lou.springboot.service.TrackService;
import com.lou.springboot.utils.CookieUtils;
import com.lou.springboot.utils.IpUtils;
import com.lou.springboot.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class TrackInterceptor implements HandlerInterceptor {
    @Autowired
    private TrackService traceService;

    @Autowired
    private ReaderService readerService;

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object o) throws Exception{
        // 判断session中是否存在reader
        Reader reader = new Reader();
        String addressIp = IpUtils.getIpAddr(request); // ip地址
        String cookieReader = CookieUtils.getCookieValue(request, "reader", true);
        if (cookieReader != null) {
            reader = JsonUtils.jsonToPojo(cookieReader, Reader.class);
        } else {
            reader = readerService.getReaderByIp(addressIp);
            if (reader == null) {
                return true;
            }
        }
        // 根据用户请求信息新增track数据
        String url = request.getRequestURI(); // 请求url
        Map map = request.getParameterMap();
        String params = JsonUtils.objectToJson(map); // 请求参数
        String model = ""; // ip地址
        String method = request.getMethod(); // 获取方法

        Track track = new Track();
        track.setReaderId(reader.getId());
        track.setIp(addressIp);
        track.setBrowseUrl(url);
        track.setParams(params);
        track.setModel(model);
        track.setMethod(method);
        traceService.addTrack(track);
        return true;
    }
}
